package com.zryc.controller;

import com.zryc.service.OrderService;
import com.zryc.service.ProductServiceClient;
import com.zryc.shop.entity.Order;
import com.zryc.shop.entity.Product;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

//使用feign客户端来远程调用 shop-product服务
//@RestController
@RequestMapping("/order2")
public class OrderController2 {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductServiceClient productServiceClient;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    private  String productServiceUrl;



    @RequestMapping("/prod/{pid}/{count}/{uid}")
    public Map<String,Object> order2(@PathVariable("pid") Integer pid,@PathVariable("count") Integer count,@PathVariable("uid") Integer uid){

        Product product=productServiceClient.getProd(pid);
        //在远程调用商品服务完成之后，来制造一个服务响应延迟的效果
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        if (product.getPid()==-1){
            Map result =new HashMap();
            result.put("error_msg","下单失败，未获取刀商品信息，请稍后重试");
            return  result;
        }else{
            if (product.getStock()<count){
                Map result =new HashMap();
                result.put("error_msg","下单失败尚帕尼不足");
                return  result;
            }
        }
        Order order=new Order();
        //系统中还没有用户数据，所以用户信息写死
        order.setUid(1);
        order.setUsername("测试用户1");
        //设置当前订单的商品INFO
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);//购买数量
        orderService.save(order);
        Map result=new HashMap();
        result.put("PRODUCT_INFO",product);
        result.put("ORDER_INFO",order);
        result.put("UID",uid);

        Message<Map> message=new Message<Map>() {
            @Override
            public Map getPayload() {
                return result;
            }

            @Override
            public MessageHeaders getHeaders() {
                return null;
            }
        };
        SendResult sendResult=rocketMQTemplate.syncSend("Order:CHECKOUT_SUCCESS",message);
        System.out.println("消息队列返回"+sendResult);
        return result;
    }

    //增加一个辅助测试请求
    @RequestMapping("/message")
    public String message(){
        return "压力测试下的消息返回测试！";
    }




















}
